﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;

namespace UnityEngine.Core
{
    public class GameTimeEventArgs : EventArgs
    {
        public GameTimeEventArgs(GameTime gameTime)
        {
            this.GameTime = gameTime;
        }
        public GameTime GameTime { set; get; }
    }

    public class MachineState : StateMachineComponent
    {
        private bool TimerEnabled
        {
            get;
            set;
        }

        public float ElapsedTime
        {
            get;
            set;
        }

        public float ExpectedTime
        {
            get;
            set;
        }

        public MachineState NextState
        {
            get;
            set;
        }

        public event EventHandler<GameTimeEventArgs> StartEvent;

        public event EventHandler<GameTimeEventArgs> UpdateEvent;

        public event EventHandler<GameTimeEventArgs> TerminateEvent;

        public string StateName
        {
            get;
            set;
        }

        public StateMachineComponent Owner
        {
            get;
            set;
        }

        public MachineState(StateMachineComponent owner, string stateName)
        {
            this.Owner = owner;
            this.StateName = stateName;
        }

        public void EnableInternalTimer(float expectedTime, MachineState nextState)
        {
            this.TimerEnabled = true;
            this.ElapsedTime = 0;
            this.ExpectedTime = expectedTime;
            this.NextState = nextState;
        }

        private void Reset()
        {
            ElapsedTime = ExpectedTime = 0;
            NextState = null;
            TimerEnabled = false;
        }

        public void Start(GameTime gameTime)
        {
            if (StartEvent != null)
                StartEvent(this, new GameTimeEventArgs(gameTime));
            ElapsedTime = 0;
        }

        public void Update(GameTime gameTime)
        {
            ElapsedTime += (float)gameTime.ElapsedGameTime.TotalSeconds;
            if (ElapsedTime > ExpectedTime && TimerEnabled == true)
            {
                if (NextState != null)
                    this.Owner.ChangeToState(NextState.StateName);
                return;
            }

            if (UpdateEvent != null)
                UpdateEvent(this, new GameTimeEventArgs(gameTime));

            base.Update(gameTime);
        }

        public void Terminate(GameTime gameTime)
        {
            if (TerminateEvent != null)
                TerminateEvent(this, new GameTimeEventArgs(gameTime));
        }
    }
}
